<template>
  <div>
    <basic-container>
      <div class="offer-info-border">
        <!--        <div>-->
        <!--          <div>在线素材</div>-->
        <!--          <div class="offer-oc-box">-->
        <!--            <div>{{ offerOnlineInfo.creativeOnlineCount.toLocaleString() }}</div>-->
        <!--          </div>-->
        <!--        </div>-->
        <div style="margin-left: 2em;margin-right: 3em;">
          <div>有效账户</div>
          <div class="offer-oc-box">
            <div>{{ offerOnlineInfo.activeAccountCount.toLocaleString() }}</div>
          </div>
        </div>
        <div>
          <div>违规素材</div>
          <div class="offer-oc-box">
            <div>{{ offerOnlineInfo.nopassCreativeOnlineCount.toLocaleString() }}</div>
          </div>
        </div>
        <!--<div>-->
        <!--<div>媒体拒绝素材</div>-->
        <!--<div class="offer-oc-box">-->
        <!--<div>{{ offerOnlineInfo.refusedCreativeCount.toLocaleString() }}</div>-->
        <!--</div>-->
        <!--</div>-->
      </div>
      <div class="cost-install-border">
        <div>
          <div class="cost-install-title">过去7天花费/安装数</div>
          <div style="display: flex">
            <div v-if="costPie" style="width: 35%;text-align: center;padding-top: 75px">
              <div class="cost-install-total-title">花费总计</div>
              <div class="cost-install-spendBand-title">
                <div class="cost-install-spendBand">
                  {{ totalBrand('cost') }}
                </div>
              </div>
            </div>
            <div v-else style="width: 35%;text-align: center;padding-top: 75px">
              <div class="cost-install-total-title">安装数总计</div>
              <div class="cost-install-spendBand-title">
                <div class="cost-install-spendBand">
                  {{ totalBrand('installs') }}
                </div>
              </div>
            </div>
            <div style="width: 65%">
              <div v-show="costPie" id="costPie" :style="{width:'300px',height:'245px'}"></div>
              <div v-show="!costPie" id="installPie" :style="{width:'300px',height:'245px'}"></div>
            </div>
          </div>
        </div>
        <div class="cost-install-changeBox">
          <div @click="costPie = true" :class="{'costpie-true': costPie}">花费</div>
          <div @click="costPie = false" :class="{'costpie-true': !costPie}">安装数</div>
        </div>
      </div>
    </basic-container>
    <!--素材在线情况-->
    <!--    <basic-container>-->
    <!--      <div class="welLabel">素材在线情况 <span class="lastDayStyle">(截止{{ yesterday }})</span></div>-->
    <!--      <div>-->
    <!--        <el-table :default-sort = "{prop: 'onlineCount', order: 'descending'}" :data="accountCreativeOnlineDataList" stripe style="width: 100%" height="250">-->
    <!--          <el-table-column prop="accountName" label="账户名称">-->
    <!--            <template slot-scope="scope">-->
    <!--              {{ scope.row.accountName }}-->
    <!--            </template>-->
    <!--          </el-table-column>-->
    <!--          <el-table-column prop="onlineCount" label="在线总计" sortable :sort-method="(a,b)=>{return a.onlineCount - b.onlineCount}">-->
    <!--            <template slot-scope="scope">-->
    <!--              {{ scope.row.onlineCount.toLocaleString() }}-->
    <!--            </template>-->
    <!--          </el-table-column>-->
    <!--          <el-table-column prop="imagesOnlineCount" label="图片" sortable :sort-method="(a,b)=>{return a.imagesOnlineCount - b.imagesOnlineCount}">-->
    <!--            <template slot-scope="scope">-->
    <!--              {{ scope.row.imagesOnlineCount.toLocaleString() }}-->
    <!--            </template>-->
    <!--          </el-table-column>-->
    <!--          <el-table-column prop="videoOnlineCount" label="视频" sortable :sort-method="(a,b)=>{return a.videoOnlineCount - b.videoOnlineCount}">-->
    <!--            <template slot-scope="scope">-->
    <!--              {{ scope.row.videoOnlineCount.toLocaleString() }}-->
    <!--            </template>-->
    <!--          </el-table-column>-->
    <!--        </el-table>-->
    <!--      </div>-->
    <!--    </basic-container>-->
    <!--设计师昨日数据-->
    <basic-container>
      <div class="welLabel">设计师昨日数据 <span class="lastDayStyle">({{ yesterday }})</span></div>
      <div>
        <el-table :default-sort="{prop: 'cost', order: 'descending'}" :data="designerDataList" stripe
                  style="width: 100%" height="250">
          <el-table-column prop="designerName" label="设计师"/>
          <el-table-column prop="installs" label="安装" sortable
                           :sort-method="(a,b)=>{return a.installs[0] - b.installs[0]}">
            <template slot-scope="scope">
              <div style="display: flex">
                <div>
                  {{ scope.row.installs[0].toLocaleString() }}
                </div>
                <div class="table-img" v-if="scope.row.installsIncrease != 0 ">
                  <img :src="valueArrowImage(scope.row.installsIncrease)" alt="">
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="installsIncrease" label="涨幅" sortable
                           :sort-method="(a,b)=>{return a.installsIncrease - b.installsIncrease}">
            <template slot-scope="scope">
              <div :style="{color: valueColor(scope.row.installsIncrease)}">
                {{ scope.row.installsIncrease.toLocaleString() }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="cost" label="花费" sortable :sort-method="(a,b)=>{return a.cost[0] - b.cost[0]}">
            <template slot-scope="scope">
              <div style="display: flex">
                <div>
                  {{ scope.row.cost[0].toLocaleString() }}
                </div>
                <div class="table-img" v-if="scope.row.costIncrease != 0 ">
                  <img :src="valueArrowImage(scope.row.costIncrease)" alt="">
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="costIncrease" label="涨幅" sortable
                           :sort-method="(a,b)=>{return a.costIncrease - b.costIncrease}">
            <template slot-scope="scope">
              <div :style="{color: valueColor(scope.row.costIncrease)}">
                {{ scope.row.costIncrease.toLocaleString() }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </basic-container>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import Moment from "moment";
import {mapGetters} from "vuex";
import {
  queryDesignerDaysPerformance,
  queryAccountCreativeOnlinePerformance,
  queryOfferOnlinePerformance,
  queryOfferPlatformDurationPerformance
} from "@/api/wel/ocindex";
import {getDetail as getOfferDetail} from "@/api/business/offer";
import {transformObjectList, findArray, findObject} from "@/util/util";
import {getSysDictList} from "@/api/system/dict";

export default {
  name: "ocIndexRight",
  data() {
    return {
      yesterday: "",
      offerInfo: null,
      costPie: true,
      pieTotal: {
        cost: 0,
        installs: 0,
      },
      designerDataList: [],
      accountCreativeOnlineDataList: [],
      offerOnlineInfo: {
        creativeOnlineCount: 0,
        activeAccountCount: 0,
        nopassCreativeOnlineCount: 0,
        refusedCreativeCount: 0,
      },
    }
  },
  created() {
  },
  computed: {
    ...mapGetters(["permission", "roles", "userInfo", "offer"]),
  },
  watch: {
    offer: {
      deep: true,
      handler(val, old) {
        if (val == '' || val == old) {
          return;
        }
        this.$nextTick(() => {
          this.init();
        })
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.init();
    })
  },
  methods: {
    loadOfferInfo(offerId, success) {
      if (offerId != null && offerId != '' && success) {
        getOfferDetail(offerId).then((res) => {
          success(res.data.data);
        }).catch(() => {
          success(null);
        });
      }
    },
    getEchartsInst(eleName) {
      let ele = document.getElementById(eleName);
      let myInst = echarts.getInstanceByDom(ele);
      if (myInst) {
        return myInst;
      } else {
        return echarts.init(ele);
      }
    },
    init() {
      this.loadOfferInfo(this.offer, (offerInfo) => {
        this.offerInfo = offerInfo;
      });

      this.yesterday = Moment(new Date()).subtract(1, 'days').format('YYYY-MM-DD');

      this.offerOnlinePerformance();
      this.offerPlatformDurationEchart();
      this.designerYesterdayTable();
      this.accountCreativeOnlineYesterdayTable();
    },

    totalBrand(propName) {
      if (propName == 'cost')
        return '$' + this.pieTotal[propName].toLocaleString();
      if (propName == 'installs')
        return this.pieTotal[propName].toLocaleString();
    },
    // 饼形图
    async pieCharts(id, data, propName) {
      let platforms = [
        {value: 'google', label: 'Google'},
        {value: 'facebook', label: 'Facebook'},
        {value: 'bigo', label: 'Bigo'},
        {value: 'tiktok', label: 'Tiktok'},
      ];
      await getSysDictList('platforms').then(map=>{
        platforms = transformObjectList(map['platforms'],[
          {from: 'dictKey', to: 'value'},
          {from: 'dictValue', to: 'label'},
        ]);
      });
      let totalValue = 0;
      let seriesData = [];
      platforms.forEach((platform) => {
        let row = findObject(data, platform.value, 'platform');
        if (row != null) {
          seriesData.push({
            name: platform.label,
            value: row[propName],
          });
          totalValue += 1 * row[propName];
        } else {
          seriesData.push({
            name: platform.label,
            value: 0,
          });
        }
      });
      this.pieTotal[propName] = totalValue;
      let myCharts = this.getEchartsInst(id);
      let option = {
        // title: {
        //   text: 'Referer of a Website',
        //   subtext: 'Fake Data',
        //   left: 'center'
        // },
        tooltip: {
          trigger: 'item'
        },
        // legend: {
        //   orient: 'vertical',
        //   left: 'left'
        // },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: '50%',
            data: seriesData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      option && myCharts.setOption(option);
    },

    calcIncRate(toVal, fromVal) {
      if (toVal == fromVal) {
        return 0;
      }
      if (fromVal == 0) {
        return 1;
      }
      if (toVal == 0) {
        return -1;
      }
      return (toVal - fromVal) / fromVal;
    },
    getIncText(incVal) {
      let sign = '';
      if (incVal > 0) {
        sign = '+';
      }
      if (incVal < 0) {
        sign = '-';
      }
      let midVal = Math.round(Math.abs(incVal) * 10000).toString();
      while (midVal.length < 3) {
        midVal = '0' + midVal;
      }
      return sign + midVal.substring(0, midVal.length - 2) + '.' + midVal.substring(midVal.length - 2) + '%';
    },
    designerYesterdayTable(data = null) {
      let days = 2;
      if (data == null) {
        queryDesignerDaysPerformance({offerId: this.offer, days: days}).then((res) => {
          if (res.data.success) {
            this.designerYesterdayTable(res.data.data);
          }
        });
        return;
      }
      let yesterdayReportDate = Moment(new Date()).subtract(1, 'days').format('YYYY-MM-DD');
      let theDayBeforeYesterdayReportDate = Moment(new Date()).subtract(2, 'days').format('YYYY-MM-DD');

      let resultDataList = [];
      data.forEach((row) => {
        let reportDate = Moment(new Date(row.reportDate)).format('YYYY-MM-DD');
        if (reportDate == yesterdayReportDate || reportDate == theDayBeforeYesterdayReportDate) {
          let rowDataIdx = findArray(resultDataList, row.userId, 'userId');
          let rowData = null;
          if (rowDataIdx == -1) {
            rowData = {
              userId: row.userId,
              designerName: row.designerName,
              impressions: [0, 0],
              clicks: [0, 0],
              installs: [0, 0],
              cost: [0, 0],
            };
            resultDataList.push(rowData);
          } else {
            rowData = resultDataList[rowDataIdx];
          }
          if (reportDate == yesterdayReportDate) {
            rowData.impressions[0] = row.impressions;
            rowData.clicks[0] = row.clicks;
            rowData.installs[0] = row.installs;
            rowData.cost[0] = row.cost;
          }
          if (reportDate == theDayBeforeYesterdayReportDate) {
            rowData.impressions[1] = row.impressions;
            rowData.clicks[1] = row.clicks;
            rowData.installs[1] = row.installs;
            rowData.cost[1] = row.cost;
          }
        }
      });
      resultDataList.forEach(row => {
        row.installsIncrease = row.installs[0] - row.installs[1];
        row.costIncrease = row.cost[0] - row.cost[1];
      });
      resultDataList.sort((a, b) => {
        if (a.cost[0] > b.cost[0]) {
          return -1;
        }
        if (a.cost[0] < b.cost[0]) {
          return 1;
        }
        if (a.installs[0] > b.installs[0]) {
          return -1;
        }
        if (a.installs[0] < b.installs[0]) {
          return 1;
        }
        return 0;
      });
      this.designerDataList = resultDataList;
    },
    accountCreativeOnlineYesterdayTable(data = null) {
      let days = 1;
      if (data == null) {
        queryAccountCreativeOnlinePerformance({offerId: this.offer, days: days}).then((res) => {
          if (res.data.success) {
            this.accountCreativeOnlineYesterdayTable(res.data.data);
          }
        });
        return;
      }
      this.accountCreativeOnlineDataList = data;
    },
    offerOnlinePerformance(data = null) {
      if (data == null) {
        queryOfferOnlinePerformance({offerId: this.offer}).then((res) => {
          if (res.data.success) {
            this.offerOnlinePerformance(res.data.data);
          }
        });
        return;
      }
      if (data.length == 1) {
        this.offerOnlineInfo = data[0];
      }
    },
    offerPlatformDurationEchart(data = null) {
      let days = 7;
      if (data == null) {
        queryOfferPlatformDurationPerformance({offerId: this.offer, days: days}).then((res) => {
          if (res.data.success) {
            this.offerPlatformDurationEchart(res.data.data);
          }
        });
        return;
      }
      this.pieCharts('costPie', data, 'cost');
      this.pieCharts('installPie', data, 'installs');
    },
    valueColor(incVal) {
      return incVal > 0 ? '#1d953f' : incVal < 0 ? '#b22c46' : 'black';
    },
    valueArrowImage(incVal) {
      return incVal > 0 ? '/img/icon/rise.png' : incVal < 0 ? '/img/icon/down.png' : '';
    },
  }
}
</script>

<style scoped lang="scss">
.offer-info-border {
  display: flex;
  //justify-content: space-between;
  text-align: center;
  font-size: 18px;
  font-weight: 700;

  :nth-child(1) .offer-oc-box {
    border-color: #045fb4;
    color: #045fb4;
  }

  :nth-child(2) .offer-oc-box {
    border-color: #088A08;
    color: #088A08;
  }

  :nth-child(3) .offer-oc-box {
    border-color: #FF4949;
    color: #FF4949;
  }

  :nth-child(4) .offer-oc-box {
    border-color: #FF7F50;
    color: #FF7F50;
  }

}

.offer-oc-box {
  margin-top: 10px;
  width: 100px;
  height: 100px;
  border: 5px solid;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
  font-weight: 700;
}

.cost-install-border {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;

  .cost-install-title {
    font-weight: 700;
    margin-left: 10px;
    font-size: 21px;
  }

  .cost-install-total-title {
    color: red;
    font-weight: 600;
    font-size: 20px;
  }
}

.cost-install-changeBox {
  width: 100px;
  padding-top: 100px;

  div {
    width: 70px;
    height: 30px;
    text-align: center;
    border: 1px solid #dcdfe6;
    border-radius: 8px;
    line-height: 30px;
    margin-bottom: 10px;
    color: #606266;
    font-size: 14px;
  }

  div:hover {
    color: #3a8ee6;
    border-color: #3a8ee6;
    background-color: #ecf5ff;
    outline: 0;
  }

  .costpie-true {
    color: white;
    border-color: #409eff;
    background-color: #409eff;
    outline: 0;
  }
}


.offer-oc-box:nth-of-type(1) {
  border-color: red;
}

.welLabel {
  font-size: 17px;
  font-weight: bold;
  color: #409eff;
  margin-left: 20px;
}

.lastDayStyle {
  color: black;
  font-size: 16px;
  margin-left: 15px;
}

.table-img {
  width: 17px;
  margin-left: 10px;
  height: 23px;

  img {
    width: 100%;
    height: 100%;
  }
}

.cost-install-spendBand {
  padding: 3px;
  background: blue;
  color: white;
  margin-right: 2px;
  border-radius: 4px;
  font-size: 20px
}

.cost-install-spendBand-title {
  display: flex;
  margin-top: 10px;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
}
</style>
